package com.sunwayworld.basemodule.business.utils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SHA256 {
    private static final String SHA256 = "HmacSHA256";
    public static String getSHA256(String message,String secret){
        String hash = "";
        try {
            Mac sha256 = Mac.getInstance(SHA256);
            SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), SHA256);
            sha256.init(secretKeySpec);
            byte[] signBytes = sha256.doFinal(message.getBytes());
            hash = byteArrayToHexString(signBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hash;
    }

    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param signBytes 字节数组
     * @return 字符串
     */
    private static String byteArrayToHexString(byte[] signBytes) {
        StringBuilder signStr = new StringBuilder();
        String signByte;
        for (int n = 0; signBytes != null && n < signBytes.length; n++) {
            signByte = Integer.toHexString(signBytes[n] & 0XFF);
            if (signByte.length() == 1){
                signStr.append('0');
            }
            signStr.append(signByte);
        }
        return signStr.toString().toLowerCase();
    }

    public static void main(String[] args) {
        String requestParam = "";  // json数据
        String appKey = "ikang-aina";  //  固定参数
        String saltKey = "@$8GoP5*M";  //  固定参数
        String s1 = MD5.getMD5(requestParam.getBytes()).toUpperCase();
        String s2 = new StringBuilder("appkey").append("=").append(appKey)
                .append("&").append("content").append("=").append(s1)
                .append("&").append("salt_key").append("=").append(saltKey).toString();
        String sign = getSHA256(s2, saltKey).toUpperCase();
        System.out.println(sign);
        // 爱康加密后的：sign = "E9BC4A808D4F686728E76103B092242B620863140C96581D106D844E92E2D461";
    }

}
